package com.hsd.znsh.location;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-05-03 11:35:44
 */
public class LocationClient {

    private String ak="FvN4DjxgKCV0HEWEtGhhK0ZKH8ojYG6W";

    private RestTemplate restTemplate=new RestTemplate();


    public void setAk(String ak) {
        this.ak = ak;
    }

    private String getAk() {
        return ak;
    }

    private String getUrl(LocationRequest locationRequest){
        BeanWrapper src = new BeanWrapperImpl(locationRequest);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        String url="http://api.map.baidu.com/location/ip?";
        if(StringUtils.isEmpty(src.getPropertyValue("ak"))){
            url+="ak="+getAk();
        }else{
            url+="ak="+src.getPropertyValue("ak");
        }
        url+="&ip="+src.getPropertyValue("ip");
        LocationRequest.Coor coor=(LocationRequest.Coor)src.getPropertyValue("coor");
        if(coor==null){
            coor=LocationRequest.Coor.BD09LL;
        }
        url+="&coor="+coor.getCoor();
        return url;
    }

    public LocationResponse getRequest(LocationRequest locationRequest){
        ResponseEntity<LocationResponse> response=restTemplate.getForEntity(getUrl(locationRequest),LocationResponse.class);
        return response.getBody();
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper=new ObjectMapper();
        LocationResponse locationResponse=objectMapper.readValue("{\"address\":\"CN|\\u5e7f\\u4e1c|None|None|TENCENT|0|0\",\"content\":{\"address_detail\":{\"province\":\"\\u5e7f\\u4e1c\\u7701\",\"city\":\"\",\"district\":\"\",\"street\":\"\",\"street_number\":\"\",\"city_code\":7},\"address\":\"\\u5e7f\\u4e1c\\u7701\",\"point\":{\"y\":\"2664306.83\",\"x\":\"12623190.7\"}},\"status\":0}",LocationResponse.class);
        System.out.println(locationResponse.getContent());
    }


}
